/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers.filters;

import com.google.gson.Gson;
import controllers.FileLogServiceControl;
import controllers.NotSyntaxServiceControl;
import controllers.pipes.Persistence2SenderPipe;
import dao.DocumentTypeDAO;
import dao.FranchiseDAO;
import dao.TraceStateDAO;
import entities.*;
import facade.facadeClass;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileLock;
import java.util.*;
import org.bson.types.ObjectId;
import view.MainWindow;
import vo.TransactionPojo;
import ws.serviceNoSyntax.NotSyntaxTransactionVO;

/**
 *
 * @author Sergio
 */
public final class SenderFilter extends Thread {

    private long lines = 0;
    private Archive archive;
    private TraceStateDAO traceStateDao;
    private Trace entityTrace;
    private TraceState entityTraceState;
    private FranchiseDAO franchiseDAO;
    private DocumentTypeDAO documentTypeDAO;
    private DocumentType entityDocumentType;
    private Franchise entityFranchise;
    private facadeClass fc;
    private String checkSum;
    private int contTempVal = 0;
    private int contTempInval = 0;

    public void setArchive(Archive archive) {
        this.archive = archive;
    }

    public void setLines(long lines) {
        this.lines = lines;
    }

    public SenderFilter() {
        super("PersistenceFilter");
        System.out.println("Starting thread: " + this);
    }

    @Override
    public void run() {
        try {
            Persistence2SenderPipe theInQueueInstance = Persistence2SenderPipe.getInstance();
            while (lines == 0) {
                Thread.sleep(200);//number of lines has not been initialized, wait some time.
            }
            for (int i = 0; i < lines;) {
                String currentWord = theInQueueInstance.getElement();//read from the pipe.
                if (currentWord == null) {
                    System.out.println("There is nothing here!! PERSISTENCE");//nothing in the pipe. Wait.
                } else {
                    System.out.println(currentWord + " in the sender!!");
                    //send to persistence
                    i++;//go to the next element in the pipa
                    Send(currentWord, i);
                }
                Thread.sleep(200);//wait
            }
        } catch (InterruptedException e) {
            System.out.println("Child interrupted.");
        }
        System.out.println("Footer...");
        FileLogServiceControl control = new FileLogServiceControl();
        control.footerFile(archive.getIdMongo());
        System.out.println("Exiting (consumer).");
    }

    public int getContTempVal() {
        return contTempVal;
    }
    
    public void Send(String line, int count) {
        String[] tempTrace;
        String delimiter = "\\|";
        tempTrace = line.split(delimiter);
        if ("0".equals(tempTrace[0])) {
            String[] tTrace = new String[9];
            for (int j = 0; j < tempTrace.length - 1; j++) {
//                System.out.println(tempTrace[j + 1]);
                tTrace[j] = tempTrace[j + 1];
            }
            //Comentar si no hay mongo
            sendValid(tTrace, count);
            contTempVal++;
        } else {
            //Comentar si no hay mongo
//            sendInvalid(count);
            contTempInval++;
        }
        System.out.println("vals:"+contTempVal);
        System.out.println("Invals:"+contTempInval);
    }

    public void sendInvalid(long line) {
        NotSyntaxTransactionVO newNotSyntax = new NotSyntaxTransactionVO();

        TimeZone timeZone1 = TimeZone.getTimeZone("America/Bogota");
        Calendar calendar = new GregorianCalendar();
        calendar.setTimeZone(timeZone1);
        String date = calendar.getTime().toString();

        newNotSyntax.setBrand(MainWindow.getActiveUser().getBrandId());
        newNotSyntax.setEstablishment(MainWindow.getActiveUser().getId());
        newNotSyntax.setFileId(archive.getIdMongo());

        newNotSyntax.setTransactionLine(String.valueOf(line));
        newNotSyntax.setValidationDate(date);

        NotSyntaxServiceControl control = new NotSyntaxServiceControl();
        control.createNotSyntax(newNotSyntax);
    }

    private long convertDate(String date) {
        //0123456789101112131415
        //08:00 22/0 4 / 2 0 1 2
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(date.substring(12)), Integer.parseInt(date.substring(9, 11)),
                Integer.parseInt(date.substring(6, 8)), Integer.parseInt(date.substring(0, 2)),
                Integer.parseInt(date.substring(3, 5)));
        return cal.getTime().getTime();
    }
    private int COLA_ACTUAL = 4;
    private ArrayList<Object> propertiesListKey;
    private ArrayList<Object> propertiesListString;

    private URL getURL() throws MalformedURLException, IOException, InterruptedException {
        String satacredito_path = "SATACREDITO_PATH";
        String file_path = "config/roundrobin";
        String file_name = "roundrobincolas";
        Properties properties = new Properties();
        properties.load(new FileInputStream(System.getenv(satacredito_path) + "/"
                + file_path + "/" + file_name + ".properties"));
        Enumeration colas = properties.propertyNames();
        propertiesListKey = new ArrayList<Object>();
        propertiesListString = new ArrayList<Object>();
        String colaString;
        for (int i = 0; i < properties.size(); i++) {
            String s = colas.nextElement().toString();
            propertiesListKey.add(s);
            propertiesListString.add(properties.getProperty(s));
        }
        try {
            if (COLA_ACTUAL % propertiesListKey.size() != 0) {
                colaString = propertiesListString.get(COLA_ACTUAL).toString();
            } else {
                COLA_ACTUAL = 0;
                colaString = propertiesListString.get(COLA_ACTUAL).toString();
            }
            COLA_ACTUAL += 1;
            return new URL("http://" + colaString + "/WSQueueRest/resources/transaction/post");
        } catch (Exception e) {
            COLA_ACTUAL = 0;
            colaString = propertiesListString.get(COLA_ACTUAL).toString();
            return new URL("http://" + colaString + "/WSQueueRest/resources/transaction/post");
        }
    }

    /**
     * This method is supposed to send vald traces to the mongo
     *
     * @param tempTrace
     * @return
     */
    public boolean sendValid(String[] tempTrace, long count) {

        TransactionPojo transaction = new TransactionPojo();
        transaction.setFileId(archive.getIdMongo());
        transaction.setFileNumber((int) count);
        transaction.setName(tempTrace[2]);
        transaction.setNin(tempTrace[1]);
        transaction.setNinType(tempTrace[0].equals("CC") ? 1 : 2);
        String[] cardData = tempTrace[4].split(":");
        transaction.setCardNumber(cardData[0]);
        transaction.setCardType(tempTrace[3].equals("DEBITO") ? 1 : 2);
        transaction.setCardCode(Integer.parseInt(cardData[1]));
        transaction.setCardExpirationDate(new Date());
        transaction.setBank(new ObjectId().toString());
        transaction.setFranchise(new ObjectId().toString());
        transaction.setPurchaseDate(convertDate(tempTrace[8]));
        transaction.setPurchaseAmount(Long.valueOf(tempTrace[6]));
        transaction.setPurchaseDetail(tempTrace[7]);

        try {
//            URL url = new URL("http://192.168.0.97:8080/WSQueueRest/resources/transaction/post");
            URL url = null;
            try {
                url = getURL();
            } catch (InterruptedException ex) {
            }
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            Gson transactionJson = new Gson();
            String input = transactionJson.toJson(transaction);
            OutputStream os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException("HTTP: code : "
                        + conn.getResponseCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));
            String outransactionut;
//            System.out.println("Received from server : OK\n");
            while ((outransactionut = br.readLine()) != null) {
//                System.out.println(outransactionut);
            }
            conn.disconnect();
        } catch (MalformedURLException e) {
            System.out.println("Client ERROR - MalformedURL Exception: ");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Client ERROR - IOEXCEPTION: ");
            e.printStackTrace();
        }
        return true;
    }
}